<template>
  <div>
    <a-checkbox :indeterminate="indeterminate" :checked="isCheckAll" @change="onCheckAllChange">
        全部({{total}})
      </a-checkbox>
    <a-checkbox-group @change="onChange" v-model="defaultValue">
      <a-checkbox v-for="item in radioList" :key="item.prop" :value="item.prop"> {{item.label}}({{item.value}}) </a-checkbox>
    </a-checkbox-group>
  </div>

</template>

<script>
export default {
  props: {
    instance: Object
  },
  data() {
    return {
      radioList: [],
      defaultValue: [],
      indeterminate: false,
      isCheckAll: false,
    }
  },
  watch: {
    instance: {
      handler(nVal) {
        Object.assign(this, {...nVal})
        
        // console.log(this.instance)
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    total() {
      return this.radioList.reduce((pre, cur) => pre += Number(cur.value), 0)
    }
  },
  created() {
    this.initStatus()
  },
  methods: {
    initStatus(){
      const allCheckList = this.instance.radioList.map(item => item.prop)
      this.onChange(allCheckList)
    },
    onChange(checkedList) {
      this.defaultValue = checkedList
      this.indeterminate = !!checkedList.length && checkedList.length < this.defaultValue.length
      this.isCheckAll = checkedList.length === this.radioList.length
      this.emitEvent()
    },
    onCheckAllChange(e) {
      Object.assign(this, {
        defaultValue: e.target.checked ? this.radioList.map(item=>item.prop) : [],
        indeterminate: false,
        isCheckAll: e.target.checked,
      });
      this.emitEvent()
    },
    emitEvent() {
      const {cb} = this.instance
      const checkedList = this.defaultValue.map(item => {
        const target = this.instance.radioList.find(t => t.prop === item)
        return target
      })
      const param = {
        checkedList,
        cb
      }
      if(this.isCheckAll) param.patentCount = this.defaultValue.length
      this.$emit('actionClick', param)
    }
  }
}
</script>
